import router from '@/router/index'
import { isNavigationFailure, NavigationFailureType } from 'vue-router'
import type { RouteRecordRaw, RouteLocationRaw } from 'vue-router'
import { ElNotification } from 'element-plus'
import { useConfig } from '@/stores/config'
import { closeShade } from '@/utils/pageShade'
// import { compact, reverse } from 'lodash-es'

/**
 * 导航失败有错误消息的路由push
 * @param to — 导航位置，同 router.push
 */
export const routePush = async (to: RouteLocationRaw) => {
  try {
    const failure = await router.push(to)
    if (isNavigationFailure(failure, NavigationFailureType.aborted)) {
      ElNotification({
        message: 'utils。导航失败，导航卫士拦截！',
        type: 'error'
      })
    } else if (isNavigationFailure(failure, NavigationFailureType.duplicated)) {
      // ElNotification({
      //   message: 'utils。导航失败，在导航目标位置！',
      //   type: 'warning'
      // })
    }
  } catch (error) {
    ElNotification({
      message: 'utils。导航失败，路线无效！',
      type: 'error'
    })
    console.error(error)
  }
}

/**
 * 获取第一个菜单
 */
export const getFirstRoute = (
  routes: RouteRecordRaw[],
  menuType = 'tab'
): false | RouteRecordRaw => {
  const routerPaths: string[] = []
  const routers = router.getRoutes()
  routers.forEach((item) => {
    if (item.path) routerPaths.push(item.path)
  })
  let find: boolean | RouteRecordRaw = false
  for (const key in routes) {
    if (
      routes[key].meta?.type == 'menu' &&
      routes[key].meta?.menu_type == menuType &&
      routerPaths.indexOf(routes[key].path) !== -1
    ) {
      return routes[key]
    } else if (routes[key].children && routes[key].children?.length) {
      find = getFirstRoute(routes[key].children!)
      if (find) return find
    }
  }
  return find
}

/**
 * 打开侧边菜单
 * @param menu 菜单数据
 */
export const onClickMenu = (menu: RouteRecordRaw) => {
  routePush({ path: menu.path })
  const config = useConfig()
  if (config.layout.mobile) {
    closeShade(() => {
      config.setLayout('menuCollapse', true)
    })
  }
}

// /**
//  * 获取菜单的paths
//  */
// export const getMenuPaths = (menus: RouteRecordRaw[]): string[] => {
//   let menuPaths: string[] = []
//   menus.forEach((item) => {
//     menuPaths.push(item.path)
//     if (item.children && item.children.length > 0) {
//       menuPaths = menuPaths.concat(getMenuPaths(item.children))
//     }
//   })
//   return menuPaths
// }

// /**
//  * 动态添加路由-带子路由
//  * @param viewsComponent
//  * @param routes
//  * @param parentName
//  * @param analyticRelation 根据 name 从已注册路由分析父级路由
//  */
// export const addRouteAll = (
//   viewsComponent: Record<string, any>,
//   routes: any,
//   parentName: string,
//   analyticRelation = false
// ) => {
//   for (const idx in routes) {
//     if (routes[idx].extend == 'add_menu_only') {
//       continue
//     }
//     if (
//       (routes[idx].menu_type == 'tab' && viewsComponent[routes[idx].component]) ||
//       routes[idx].menu_type == 'iframe'
//     ) {
//       addRouteItem(viewsComponent, routes[idx], parentName, analyticRelation)
//     }
//
//     if (routes[idx].children && routes[idx].children.length > 0) {
//       addRouteAll(viewsComponent, routes[idx].children, parentName, analyticRelation)
//     }
//   }
// }

// /**
//  * 动态添加路由
//  * @param viewsComponent
//  * @param route
//  * @param parentName
//  * @param analyticRelation 根据 name 从已注册路由分析父级路由
//  */
// export const addRouteItem = (
//   viewsComponent: Record<string, any>,
//   route: any,
//   parentName: string,
//   analyticRelation: boolean
// ) => {
//   let path = ''
//   let component
//   if (route.menu_type == 'iframe') {
//     // path =
//     //   (isAdminApp() ? adminBaseRoute.path : memberCenterBaseRoute.path) +
//     //   '/iframe/' +
//     //   encodeURIComponent(route.url)
//     // component = () => import('@/layouts/common/router-view/iframe.vue')
//   } else {
//     path = parentName ? route.path : '/' + route.path
//     component = viewsComponent[route.component]
//   }
//
//   if (route.menu_type == 'tab' && analyticRelation) {
//     const parentNames = getParentNames(route.name)
//     if (parentNames.length) {
//       for (const key in parentNames) {
//         if (router.hasRoute(parentNames[key])) {
//           parentName = parentNames[key]
//           break
//         }
//       }
//     }
//   }
//
//   const routeBaseInfo: RouteRecordRaw = {
//     path,
//     name: route.name,
//     component,
//     meta: {
//       title: route.title,
//       extend: route.extend,
//       icon: route.icon,
//       keepalive: route.keepalive,
//       menu_type: route.menu_type,
//       type: route.type,
//       url: route.url,
//       addtab: true
//     }
//   }
//   if (parentName) {
//     router.addRoute(parentName, routeBaseInfo)
//   } else {
//     router.addRoute(routeBaseInfo)
//   }
// }

// /**
//  * 根据name字符串，获取父级name组合的数组
//  * @param name
//  */
// const getParentNames = (name: string) => {
//   const names = compact(name.split('/'))
//   const tempNames = []
//   const parentNames = []
//   for (const key in names) {
//     tempNames.push(names[key])
//     if (parseInt(key) != names.length - 1) {
//       parentNames.push(tempNames.join('/'))
//     }
//   }
//   return reverse(parentNames)
// }

// /**
//  * 寻找当前路由在顶栏菜单中的数据
//  */
// export const currentRouteTopActivity = (
//   path: string,
//   menus: RouteRecordRaw[]
// ): RouteRecordRaw | false => {
//   for (let i = 0; i < menus.length; i++) {
//     const item: RouteRecordRaw = menus[i]
//     // 找到目标
//     if (item.path == path) return item
//     // 从子级继续寻找
//     if (item.children && item.children.length > 0) {
//       const find = currentRouteTopActivity(path, item.children)
//       if (find) return item
//     }
//   }
//   return false
// }
